package com.pictures;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import com.ftl.framework.BitmapImg;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.PixelFormat;
import android.graphics.Bitmap.CompressFormat;
import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
import android.hardware.Camera.ShutterCallback;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;

public class CamaraView extends Activity implements SurfaceHolder.Callback
		 {
	
	public static int FOTO_MODE = 0;
	public static int FOTO_QUALITY = 100;
	public static int FOTO_WIDTH = 1024;
	public static int FOTO_HEIGHT = 768;
	
	private static final String TAG = "CameraTest";
	private static final String SDCARD = "/sdcard/";
	
	private char posicion = 'V';
	
	
	private String sNombreImg;
	//Camera mCamera;
	//boolean mPreviewRunning = false;
	private Context mContext = this;

	Camera camera;
	SurfaceView surfaceView;
	SurfaceHolder surfaceHolder;
	boolean previewing = false;
	LayoutInflater controlInflater = null;	
	
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.camara);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        
        getWindow().setFormat(PixelFormat.UNKNOWN);
        surfaceView = (SurfaceView)findViewById(R.id.camerapreview);
        surfaceHolder = surfaceView.getHolder();
        surfaceHolder.addCallback(this);
        surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        
        controlInflater = LayoutInflater.from(getBaseContext());
        View viewControl = controlInflater.inflate(R.layout.control, null);
        LayoutParams layoutParamsControl 
        	= new LayoutParams(LayoutParams.FILL_PARENT, 
        	LayoutParams.FILL_PARENT);
        this.addContentView(viewControl, layoutParamsControl);
        
        Button buttonTakePicture = (Button)findViewById(R.id.takepicture);
        buttonTakePicture.setOnClickListener(new Button.OnClickListener(){

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				camera.takePicture(myShutterCallback, 
						myPictureCallback_RAW, myPictureCallback_JPG);
			}});
    }
	
    ShutterCallback myShutterCallback = new ShutterCallback(){

		@Override
		public void onShutter() {
			// TODO Auto-generated method stub
			
		}};
		
	PictureCallback myPictureCallback_RAW = new PictureCallback(){

		@Override
		public void onPictureTaken(byte[] arg0, Camera arg1) {
			// TODO Auto-generated method stub
			
		}};
		
	PictureCallback myPictureCallback_JPG = new PictureCallback(){

		@Override
		public void onPictureTaken(byte[] imageData, Camera arg1) {
			// TODO Auto-generated method stub
			//Bitmap bitmapPicture 
			//	= BitmapFactory.decodeByteArray(imageData, 0, imageData.length);
			
			if (imageData != null) {

				Intent mIntent = new Intent();
				
				sNombreImg = String.format("%d.jpg",System.currentTimeMillis());
				
				
				StoreByteImage(mContext, imageData, CamaraView.FOTO_QUALITY, sNombreImg);
				camera.startPreview();
				
				Bundle params = new Bundle();
				params.putString("FOTO_SRC", SDCARD + sNombreImg);
				params.putChar("FOTO_POSICION", posicion);
				
				mIntent.putExtras(params);
				
				setResult(FOTO_MODE, mIntent);
				finish();

			}
			
			
			
			
			
			
		}};

	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {
		// TODO Auto-generated method stub
		if(previewing){
			camera.stopPreview();
			previewing = false;
		}
		
		if (camera != null){
			try {
				camera.setPreviewDisplay(surfaceHolder);
				camera.startPreview();
				previewing = true;
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		// TODO Auto-generated method stub
		camera = Camera.open();
	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		// TODO Auto-generated method stub
		camera.stopPreview();
		camera.release();
		camera = null;
		previewing = false;
	}	

	public static boolean StoreByteImage(Context mContext, byte[] imageData,
			int quality, String expName) {

	

		BitmapFactory.Options options=new BitmapFactory.Options();
		options.inSampleSize = 5;
		
		Bitmap myImage = BitmapFactory.decodeByteArray(imageData, 0,
				imageData.length,options);
		
		
    	OutputStream os = null; 
        try { 
          os = new FileOutputStream(SDCARD + expName); 
          myImage.compress(CompressFormat.PNG, FOTO_QUALITY , os); 
        } catch(IOException e) { 
          Log.e("combineImages", "problem combining images", e); 
          return false;
        }


		return true;
	}	
	
	
	
	/*
	
	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
	}

	Camera.PictureCallback mPictureCallback = new Camera.PictureCallback() {
		public void onPictureTaken(byte[] imageData, Camera c) {

			if (imageData != null) {

				Intent mIntent = new Intent();
				
				sNombreImg = String.format("%d.jpg",System.currentTimeMillis());
				
				Toast.makeText(mContext, sNombreImg, Toast.LENGTH_SHORT);
				
				StoreByteImage(mContext, imageData, CamaraView.FOTO_QUALITY, sNombreImg);
				mCamera.startPreview();
				
				Bundle params = new Bundle();
				params.putString("FOTO_SRC", SDCARD + sNombreImg);
				params.putChar("FOTO_POSICION", posicion);
				
				mIntent.putExtras(params);
				
				setResult(FOTO_MODE, mIntent);
				finish();

			}
		}
	};

	protected void onResume() {
		Log.e(TAG, "onResume");
		super.onResume();
	}

	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
	}

	protected void onStop() {
		Log.e(TAG, "onStop");
		super.onStop();
	}

	public void surfaceCreated(SurfaceHolder holder) {
		Log.e(TAG, "surfaceCreated");
		mCamera = Camera.open();
		try {
			mCamera.setPreviewDisplay(holder);
			
		
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}		

	}

	public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
		Log.e(TAG, "surfaceChanged");

		Camera.Parameters p = mCamera.getParameters();

		// XXX stopPreview() will crash if preview is not running
		if (mPreviewRunning) {
			
			
			mCamera.stopPreview();
			
			
			
		}

		if (w > h){
			this.posicion = 'H';
			p.setPictureSize(CamaraView.FOTO_WIDTH,CamaraView.FOTO_HEIGHT);
			p.setPreviewSize(w, h);
			
		}
		else
		{
			this.posicion = 'V';
			p.setPictureSize(CamaraView.FOTO_HEIGHT,CamaraView.FOTO_WIDTH);
			p.setPreviewSize(h, w);
		}
		
		mCamera.setParameters(p);
		

		mCamera.startPreview();
		mPreviewRunning = true;
        
		
	}

	public void surfaceDestroyed(SurfaceHolder holder) {
		Log.e(TAG, "surfaceDestroyed");
		mCamera.stopPreview();
		mPreviewRunning = false;
		mCamera.release();
	}

	private SurfaceView mSurfaceView;
	private SurfaceHolder mSurfaceHolder;

	public void onClick(View arg0) {

		mCamera.takePicture(null, mPictureCallback, mPictureCallback);

	}
	
	public static boolean StoreByteImage(Context mContext, byte[] imageData,
			int quality, String expName) {

        File sdImageMainDirectory = new File(SDCARD);
		FileOutputStream fileOutputStream = null;
		String nameFile;
		try {

			BitmapFactory.Options options=new BitmapFactory.Options();
			options.inSampleSize = 5;
			
			Bitmap myImage = BitmapFactory.decodeByteArray(imageData, 0,
					imageData.length,options);
			
			BitmapImg bmpFinal = new BitmapImg(myImage);
			boolean bRes = bmpFinal.save(SDCARD + expName);
			
			/*
			fileOutputStream = new FileOutputStream(
					sdImageMainDirectory.toString() + "/" + expName);
							
  
			BufferedOutputStream bos = new BufferedOutputStream(
					fileOutputStream);

			myImage.compress(CompressFormat.JPEG, quality, bos);

			bos.flush();
			bos.close();
		} catch (Exception e)
		{
			e.printStackTrace();
		} 
		/*catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
			Toast.makeText(mContext, e.getMessage(), Toast.LENGTH_LONG);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
			Toast.makeText(mContext, e.getMessage(), Toast.LENGTH_LONG);
		}

		return true;
	}*/
	


}